package com.wanglibao.woodtrade.woodtrade.ui.fragment;


import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.wanglibao.woodtrade.woodtrade.R;
import com.wanglibao.woodtrade.woodtrade.config.NetConfig;
import com.wanglibao.woodtrade.woodtrade.entity.MyGMOrderDetails;
import com.wanglibao.woodtrade.woodtrade.jsonrpc.JsonRPCAsyncTask;
import com.wanglibao.woodtrade.woodtrade.model.impl.UserImpl;
import com.wanglibao.woodtrade.woodtrade.ui.activity.adapter.ItemLvMyGMOrderFragmentAdapter;
import com.wanglibao.woodtrade.woodtrade.util.PullUtil;
import com.wanglibao.woodtrade.woodtrade.util.ToastUtil;
import com.wanglibao.woodtrade.woodtrade.widget.PullToRefreshView.PullToRefreshBase;
import com.wanglibao.woodtrade.woodtrade.widget.PullToRefreshView.PullToRefreshListView;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * A simple {@link Fragment} subclass.
 */
public class MyGMOrderFragment extends BaseFragment implements AdapterView.OnItemClickListener, PullToRefreshBase.OnRefreshListener2 {

    ItemLvMyGMOrderFragmentAdapter mAdapter;
    List<String> mList = new ArrayList<>();
    @Bind(R.id.lv_my_order_gm_fragment)
    PullToRefreshListView mLvMyOrderGmFragment;
    List<String> testtimne=new ArrayList<>();
    long begin = System.currentTimeMillis();
    //=============================
    MyGMOrderDetails myGMOrderDetails = new MyGMOrderDetails();
    Timer mTimer = new Timer();
    Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(final Message msg) {
            if(msg.arg2==20) {
                for (int i = 0; i <myGMOrderDetails.getOrder_list().size(); i++) {
                    long total;
                    if(myGMOrderDetails.getOrder_list().get(i).getOrder_status().equals("0")){
                         total = Long.parseLong(myGMOrderDetails.getOrder_list().get(i).getC_time());
                    }else {
                         total = Long.parseLong(myGMOrderDetails.getOrder_list().get(i).getPay_time());
                    }
                    long now = System.currentTimeMillis();
                    long pdata = total * 1000 + 3600 * 24 * 1000;
                    long pdata1 = total * 1000 + 3600 * 72 * 1000;
                    long left = pdata - now;
                    long left1= pdata1-now;
                    TextView textView = getTVInPostion(i);
                    if (textView != null) {
                            if(myGMOrderDetails.getOrder_list().get(i).getOrder_status().equals("2")){
                                textView.setText("");
                            }else {
                                if (myGMOrderDetails.getOrder_list().get(i).getDelay().equals("0")){
                                    if(left>0){
                                        textView.setText(convertTimeFormat(left));
                                    }else {
                                        textView.setText("");
                                    }
                                }else {
                                    if(left1>0){
                                        textView.setText(convertTimeFormat(left1));

                                    }else {
                                        textView.setText("");
                                    }
                                }
                            }

                    }
                }
            }else {
                System.out.println(msg.obj.toString());
                if (msg.arg2 == 2) {
                    if (pageNumber == 1) {
                        if (myGMOrderDetails != null) {
                            myGMOrderDetails.getOrder_list().clear();
                        }
                        mAdapter.setList(myGMOrderDetails.getOrder_list());
                    } else {
                        ToastUtil.createLongToast(getContext(), "没有更多数据了");
                        pageNumber--;
                    }
                } else {
                    MyGMOrderDetails myCSOrderDetails1 = new Gson().fromJson(msg.obj.toString(), MyGMOrderDetails.class);
                    if (pageNumber == 1) {
                        myGMOrderDetails = myCSOrderDetails1;
                    } else {
                        myGMOrderDetails.getOrder_list().addAll(myCSOrderDetails1.getOrder_list());
                    }
                    mAdapter.setList(myGMOrderDetails.getOrder_list());
                    mTimer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            Message message=mHandler.obtainMessage();
                            message.arg2=20;
                            mHandler.sendMessage(message);

                        }
                    }, 0, 1000);

                }

            }
            if(mLvMyOrderGmFragment!=null){
                mLvMyOrderGmFragment.onRefreshComplete();
            }

            return false;
        }
    });

    public int zhuangtai=1;
    public int pageNumber = 1;
    public MyGMOrderFragment() {

    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_my_gmorder, container, false);
        ButterKnife.bind(this, view);
        System.out.println("MyOrderActivity+Token"+new UserImpl(getContext()).getUser().token);
        initView();
        NetWorking(4);

        return view;
    }
        public TextView getTVInPostion(int positon) {
            for (TextView textView : mAdapter.mTextViews_left_time) {
                if ((Integer)textView.getTag() == positon) {
                    return textView;
                }
            }
            return null;
        }

        //把毫秒值转换成时.分.秒格式
        public String convertTimeFormat(long timeAll){
            int day=(int)(timeAll/(1000*60*60*24));
            int timeleft0=(int) (timeAll%(1000*60*60*24));
            int hour= timeleft0/(1000*60*60);
            int timeleft1= (int) (timeAll%(1000*60*60));
            int minute= timeleft1/(1000*60);
            int timeleft2= (int) (timeAll%(1000*60));
            int second= timeleft2/1000;
            if(day>0){
                return "剩余时间："+day+"天"+hour+"时"+minute+"分"+second+"秒";
            }else {
                return "剩余时间："+hour+"时"+minute+"分"+second+"秒";
            }
        }


        private void initView() {
        //通用 初始化
        myGMOrderDetails = new MyGMOrderDetails();
        myGMOrderDetails.setOrder_list(new ArrayList<MyGMOrderDetails.OrderListBean>());
        mAdapter = new ItemLvMyGMOrderFragmentAdapter(getContext(), myGMOrderDetails.getOrder_list(),this);
        mLvMyOrderGmFragment.getRefreshableView().setAdapter(mAdapter);
        mLvMyOrderGmFragment.getRefreshableView().setOnItemClickListener(this);
        mLvMyOrderGmFragment.setMode(PullToRefreshBase.Mode.BOTH);
        mLvMyOrderGmFragment.getRefreshableView().setSelector(new ColorDrawable(Color.TRANSPARENT));
        mLvMyOrderGmFragment.setOnRefreshListener(this);
        PullUtil.initIndicator(mLvMyOrderGmFragment);
    }

    public void NetWorking(int status) {
        zhuangtai=status;
        //SERVER_wangliwei
        JsonRPCAsyncTask jsonRPCAsyncTask = new JsonRPCAsyncTask(false,this, NetConfig.SERVER  + NetConfig.TYPE_ORDER,
                NetConfig.order_list, mHandler,
                "jsonObject", NetConfig.TaskId.order_list,
                new Object[]{pageNumber, zhuangtai, new UserImpl(getContext()).getUser().token, 0});
        jsonRPCAsyncTask.execute(new Void[]{});
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
        mTimer.cancel();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        pageNumber = 1;
        NetWorking(zhuangtai);
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        pageNumber++;
        NetWorking(zhuangtai);
    }
}
